package edu.itla.medifacil.persistence.managers;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.Prescription;

public class PrescriptionManager {
	private EntityManager em = null;
	
	public PrescriptionManager() {
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	
	public Prescription save( Map<String, String> parameters ){
		Prescription prescription = new Prescription();
		PersonManager personManager = new PersonManager();
		SufferingManager sufferingManager = new SufferingManager();
		
		if( parameters.get("id") != null && parameters.get("id").trim().length() > 0 )
			prescription = this.find( Integer.parseInt( parameters.get("id") ) );
	 	
		prescription.setDrugs( parameters.get("drugs") );
		prescription.setPatient( personManager.find( Integer.parseInt( parameters.get("patientId") ) ) );
		prescription.setSuffering( sufferingManager.find( Integer.parseInt( parameters.get("sufferingId") ) ) );
		
		em.getTransaction().begin();
		em.persist(prescription);
		em.getTransaction().commit();
		
		return this.find( prescription.getId() );
	}
	
	
	public Prescription find( int testId ){
		em.clear();
		return em.find( Prescription.class, testId);
	}
	
	@SuppressWarnings("unchecked")
	public List<Prescription> findAll(){
		return (List<Prescription>) em.createQuery( "SELECT p FROM Prescription p").getResultList();
	}
}
